package com.example.cloudmusic.home.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.cloudmusic.databinding.ItemRecommendedMusicBinding
import com.example.cloudmusic.home.model.Music

/**
 * 歌曲适配器
 */
class MusicAdapter : BaseListAdapter<Music, MusicAdapter.ViewHolder>(MusicDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemRecommendedMusicBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ViewHolder(private val binding: ItemRecommendedMusicBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {
            binding.root.setOnClickListener { onItemClick(adapterPosition) }

            binding.cmPlayButton.setOnClickListener {
                Toast.makeText(it.context, "播放按钮", Toast.LENGTH_SHORT).show()
            }
        }

        fun bind(item: Music) {
            binding.apply {
                cmSongTitle.text = item.title
                cmArtistName.text = item.artist

                Glide.with(root)
                    .load(item.imageUrl)
                    .into(cmSongCover)
            }
        }
    }

    private class MusicDiffCallback : DiffUtil.ItemCallback<Music>() {
        override fun areItemsTheSame(oldItem: Music, newItem: Music): Boolean =
            oldItem.id == newItem.id

        override fun areContentsTheSame(oldItem: Music, newItem: Music): Boolean =
            oldItem.title == newItem.title &&
                    oldItem.artist == newItem.artist &&
                    oldItem.imageUrl == newItem.imageUrl
    }
}